package com.lfy.ch01.tcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

public class HelloTcpClient {


    //TCP：三次握手
    public static void main(String[] args) throws IOException {

        //1、创建 Socket 对象； 指定要连接哪个服务器
        try(Socket socket = new Socket("127.0.0.1", 8080);
            InputStream is = socket.getInputStream();
            OutputStream os = socket.getOutputStream();
        ){
            //2、发送消息
            System.out.println("客户端已启动，等待服务器响应...");
            Scanner scanner = new Scanner(System.in);
            while(true){
                //3、自定义录入数据
                String str = scanner.nextLine(); //读取一行输入的数据（阻塞方法：自己输入）
                os.write(str.getBytes());
                os.flush();

                //3、接收消息
                byte[] bytes = new byte[1024];
                int len;
                if((len = is.read(bytes)) != -1){
                    System.out.println("服务器回复：" + new String(bytes, 0, len));
                }
            }



        }


    }
}
